﻿using Microsoft.AspNetCore.Mvc;
using PetaPoco;
using Qy.Common;
using Qy.Models;
using Qy.Service;
using Qy.Web.Authorize;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class ContentController : Base
{
    private readonly LoginUtil _LoginUtil;
    private readonly ContentService _contentService;
    private readonly ContentCateService _contentCateService;
    private readonly ConfigService _configService;
    private readonly AttmentService _attment;
    private readonly UserService _adminUserService;
    public ContentController(LoginUtil LoginUtil, ContentService contentService, ContentCateService contentCateService,
      AttmentService attmentService, ConfigService configService, UserService adminUserService)
    {
        _LoginUtil = LoginUtil;
        _contentService = contentService;
        _contentCateService = contentCateService;
        _configService = configService;
        _attment = attmentService;
        _adminUserService = adminUserService;
    }

    /// <summary>
    /// 查询列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] ContentQuery query)
    {
        UserInfo adminUser = await _LoginUtil.UserInfoAsync();

        query.Uid = adminUser.UserId;
        query.Uids = await _adminUserService.UserPostAsUids(adminUser);

        IEnumerable<ViewContentCate> catelist = await _contentCateService.GetContentCateListAsync(adminUser, ((int)AdminRoleEnum.Role.判断权限));
        Page<ViewContentAndCate> pagedList = await _contentService.GetListByCidAdminAsync(query);
        return Json(new { status = 1, count = pagedList.TotalItems, data = pagedList.Items, catelist });
    }

    /// <summary>
    /// 增改前
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        //用户信息
        UserInfo adminUser = await _LoginUtil.UserInfoAsync();
        //栏目信息
        IEnumerable<ViewContentCate> cateList = await _contentCateService.GetContentCateListAsync(adminUser, ((int)AdminRoleEnum.Role.判断权限));
        if (id > 0)
        {
            EditContentAndContent data = await _contentService.GetEditAsync(id);
            List<ViewAttment> attments = null; //附件信息
            if (!string.IsNullOrEmpty(data.Attments))
                attments = await _attment.GetListAsync(data.Attments);
            return Json(new { status = 1, data, attments, cateList });
        }
        return Json(new { status = 1, cateList });
    }

    [HttpPost, ActionName("Create")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    [Log(Name = "新增文章")]
    public async Task<IActionResult> CreatePostAsync([FromBody] EditContentAndContent contentPost)
    {
        if (ModelState.IsValid)
        {
            UserInfo adminUser = await _LoginUtil.UserInfoAsync();

            Content content = contentPost.AsContent();
            content.Uid = adminUser.UserId;

            Content contentRes = await _contentService.InsertContentAndContentAsync(content, contentPost.AsContentContent());

            if (contentRes.Id > 1)
            {
                return Json(new { status = 1, msg = "新增内容 Id: " + contentRes.Id, cid = contentRes.Cid });
            }
            else
                return Json(new { status = 0, msg = "新增失败！" });
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { result = 0, msg = error });
        }
    }


    [HttpPut, ActionName("Edit")]
    [XssFieldFilter]//防Xss
    [ActionPermissionFilter(Permission = PermissionKeys.Content_AddOrEdit)]
    [Log(Name = "修改文章")]
    public async Task<IActionResult> EditPostAsync([FromBody] EditContentAndContent contentPost)
    {
        if (ModelState.IsValid)
        {
            int x = await _contentService.UpdateContentAndContentAsync(contentPost.AsContent(), contentPost.AsContentContent());
            if (x > 0)
            {
                return Json(new { status = 1, msg = "修改内容 ID：" + contentPost.Id, cid = contentPost.Cid });
            }
            else
            {
                return Json(new { status = 0, msg = "修改失败！" });
            }
        }
        else
        {
            var error = ModelState.GetErrorMessages();
            return Json(new { status = 0, msg = error });
        }
    }
    [HttpPut]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Status)]
    [Log(Name = "设置内容属性")]
    public async Task<IActionResult> SwitchValue([FromBody] FormChange formChange)
    {
        if (await _contentService.UpdateContentAttAsync(formChange) > 0)
        {
            string title = formChange.Val == 1 ? "设置" : "取消设置";
            return Json(new { status = 1, msg = title + formChange.Title + " ID：" + formChange.Id });
        }
        else
            return Json(new { status = 0, msg = "设置失败！" });
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Content_Delete)]
    [Log(Name = "删除文章")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _contentService.DelContentAndContentAsync(id) > 0)
        {
            return Json(new { status = 1, msg = "删除内容 ID：" + id });
        }
        else
            return Json(new { status = 0, msg = "删除失败！" });
    }
}
